package com.ygl.example.service.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.ResponseErrorHandler;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;

/**
 * author: yanggld
 * date: 2019/12/21 14:16
 * version: 1.0
 * description: MyResponseErrorHandler
 */
@Slf4j
public class MyResponseErrorHandler implements ResponseErrorHandler {

    /** 对response进行判断，如果是异常情况，返回true */
    @Override
    public boolean hasError(ClientHttpResponse response) throws IOException {
        if (response.getStatusCode() != HttpStatus.OK) {
            return true;
        }
        return  false;
    }


    /** 异常情况时的处理方法 */
    @Override
    public void handleError(ClientHttpResponse response) {
        try {
            String err = convertStreamToString(response.getBody());
            log.error("rest异常***********************"+err);
            String statusText = response.getStatusText();
            System.out.printf("------------------"+statusText);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * InputStream转成String
     * @param is InputStream
     * @return String
     */
    private String convertStreamToString(InputStream is) {

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
        }
        return sb.toString();
    }

}
